package main

import (
	"fmt"
	"github.com/faiface/beep"
	"github.com/faiface/beep/mp3"
	"github.com/faiface/beep/speaker"
	"log"
	"os"
	"time"
)

/*
  使用队列实现歌曲列表功能，将希望接下来播放的歌曲添加到播放列表
*/

type Queue struct {
	streamers []beep.Streamer
}

func (q *Queue) Stream(samples [][2]float64) (n int, ok bool) {

	filled := 0
	for filled < len(samples) {
		// 队列为空, 就静音
		if len(q.streamers) == 0 {
			for i := range samples[filled:] {
				samples[i][0] = 0
				samples[i][1] = 0
			}
			break
		}

		// queue 非空  | 1 | 2 |  3 |
		n, ok := q.streamers[0].Stream(samples[filled:])
		if !ok {
			q.streamers = q.streamers[1:]
		}
		filled += n
	}
	return len(samples), true
}

func (q *Queue) Err() error {
	log.Fatal("queue err!")
	return nil
}

func (q *Queue) Add(resampled ...beep.Streamer) {
	q.streamers = append(q.streamers, resampled...)
}

func main() {
	// 定义一个采样率
	sr := beep.SampleRate(44100)
	err :=  speaker.Init(sr, sr.N(time.Second / 10))
	if err != nil {
		log.Fatal(err)
	}
    // 定义一个播放列表
	var queue Queue
	speaker.Play(&queue)

	for {
		var name string
		fmt.Print("Type an MP3 name:")
		_, err = fmt.Scanln(&name)
		if err != nil {
			log.Fatal(err)
		}

		// Open file on the disk
		file, err := os.Open(name)
		if err != nil {
			log.Fatal(err)
			continue
		}

		// 解码
		streamer, format, err := mp3.Decode(file)
		if err != nil {
			log.Fatal(err)
			continue
		}

	//	重新取样，确保是按照44100这个采样率进行播放
		resampled := beep.Resample(6, format.SampleRate, sr, streamer)

		// and
		speaker.Lock()
		queue.Add(resampled)
		speaker.Unlock()

	}

}
